<?php

namespace app\api\model;

use think\Model;
use think\Validate;

class UserModel extends Model
{
    protected $pk = 'id';
    protected $table = 'user';

    /**
     * 登录
     * @param $data POST数据
     */
    public function login($data)
    {
        // 执行验证
        $validate = new Validate([
            'user_name' => 'require',
            'user_password' => 'require',
        ], [
            'user_name.require' => '请输入用户名',
            'user_password.require' => '请输入密码',
        ]);
        if (!$validate->check($data)) {
            return ['code' => 10110, 'msg' => $validate->getError()];
        }
        // 对比数据库
        $userInfo = $this->where('user_name', $data['user_name'])->where('user_password', $data['user_password'])->find();
        if (!$userInfo) {
            return ['code' => 10110, 'msg' => '用户名或密码错误'];
        }
        // 将用户信息存入session
        session('user.id', $userInfo['user_id']);
        session('user.name', $userInfo['user_name']);
        return ['code' => 0, 'msg' => '登录成功', 'data' => $userInfo];
    }

}
